// 1.导入express包
const express = require('express')
// 2.创建server服务器对象
const app = express()

app.use("/uploads",express.static("./uploads"))

const joi = require("@hapi/joi")

// 配置跨域
const cors = require("cors")
app.use(cors())

// 配置post参数的中间件  req身上就有了req.body
// name=jack&age=18
app.use(express.urlencoded({extended:false}))
// {name:jack,age:18}
// app.use(express.json())


// 优化res.send()方法
app.use(function(req,res,next){
    // 声明一个函数
    res.cc = function(err,status=1){
        res.send({ 
            status:status, 
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

// 注册解析token的中间件 req身上就有了req.user
const expressJwt = require("express-jwt")
const config = require("./config")
app.use(expressJwt({secret:config.jwtSecretKey,algorithms:["HS256"]}).unless({path:[/^\/api\//]}))

// 配置路由
const userRouter = require("./router/user.js")
app.use("/api",userRouter)

const userInfoRouter = require("./router/userinfo.js")
app.use("/my",userInfoRouter)

const cateRouter = require("./router/cate.js")
app.use("/my/article",cateRouter)

const articleRouter = require("./router/article.js")
app.use("/my/article",articleRouter)


// 错误级别的中间件
app.use((err,req,res,next)=>{
    if(err instanceof joi.ValidationError){
        return res.cc(err)
    } else if(err.name =="UnauthorizedError"){
        return res.cc("token不合法")
    }
    res.cc(err)

})

// 3.开启服务器
app.listen(5000,()=>{
    console.log("app is running at http://127.0.0.1:5000"); 
})